import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/entities/application/department_entity.dart';

class UnitSelectionController extends GetxController with GetSingleTickerProviderStateMixin {
  late TabController tabController; // 页面控制器
  Map<String, dynamic> queryParameters = {}; // 请求参数
  bool isRadio = true;
  List<DepartmentEntity> selectedList = []; // 选中的列表
  String departmentName = ''; // 选中的id

  @override
  void onInit() {
    super.onInit();
    tabController = TabController(length: 2, vsync: this);

    final Map<String, dynamic> arguments = Get.arguments as Map<String, dynamic>;
    //获取请求参数
    queryParameters = arguments['queryParameters'] as Map<String, dynamic>;
    //获取是否单选
    isRadio = arguments['isRadio'] as bool;
  }

  @override
  void dispose() {
    super.dispose();
    tabController.dispose();
  }

  /// 获取特殊作业列表数据
  Future<List<DepartmentEntity>> getDate(
    int pageIndex,
    int pageSize,
    int type, {
    String? search,
  }) async {
    //获取内部单位接口
    if (type == 0) {
      final res = await HttpUtil()
          .generateGetRequest<List<DepartmentEntity>>(Interface.getDepartmentList, queryParameters: {
        'pageNum': pageIndex,
        'pageSize': pageSize,
        'departmentStatus': -1, //获取全部
        'departmentName': search,
      }).execute();

      List<DepartmentEntity>? data;
      res.onSuccess((result) {
        data = result.data;
      });
      return data ?? [];
    }

    return [];
  }

  /// 选择点击事件
  void onTap(DepartmentEntity item, bool isRadio) {
    //如果是单选
    if (isRadio) {
      for (var selectItem in selectedList) {
        //清空之前选中的数据
        selectItem.setIsChecked(false);
      }
      item.setIsChecked(true);
      selectedList.clear();
      selectedList.add(item);
    } else {
      //判断点击前的状态
      final bool isChecked = item.getIsChecked();
      if (isChecked) {
        //如果之前是选中的，就修改状态后移出
        item.setIsChecked(false);
        selectedList.remove(item);
      } else {
        //如果之前是未选中的，就修改状态后添加
        item.setIsChecked(true);
        selectedList.add(item);
      }
    }
    update();
  }

  ///完成
  void complete() {
    if (selectedList.isEmpty) {
      AppToast.showWarning('请选择单位!');
      return;
    }
    Get.back(result: selectedList);
  }
}
